from django.shortcuts import render
from apps.cms.models import News, NewsCategory
from django.conf import settings
from .serializers import NewsSerializer, CommentSerializer
from utils import restful
from django.http import Http404
from .forms import PublicCommentForm
from .models import Comment, Banner
from apps.xfzauth.decorators import xfz_login_required
from django.db.models import Q


# 新闻首页
def index(request):
    count = settings.ONE_PAGE_NEWS_COUNT
    newses = News.objects.select_related('category', 'author').all()[0:count]
    categories = NewsCategory.objects.all()
    context = {
        'newses': newses,
        'categories': categories,
        'banners': Banner.objects.all()
    }
    return render(request, 'news/index.html', context=context)


# 新闻首页内的新闻列表
def news_list(request):
    page = int(request.GET.get('p', 1))
    category_id = int(request.GET.get('category_id', 0))
    start = (page - 1) * settings.ONE_PAGE_NEWS_COUNT
    end = start + settings.ONE_PAGE_NEWS_COUNT

    if category_id == 0:
        newses = News.objects.select_related('category', 'author').all()[start:end]
    else:
        newses = News.objects.select_related('category', 'author').filter(category_id=category_id)[start:end]
    serializer = NewsSerializer(newses, many=True)
    data = serializer.data
    return restful.result(data=data)


# 新闻详情页
def news_detail(request, news_id):
    try:
        news = News.objects.select_related('category', 'author').prefetch_related("comment_set__author").get(id=news_id)
        context = {
            'news': news
        }
        return render(request, 'news/news_detail.html', context=context)
    except:
        raise Http404


# 发布评论
@xfz_login_required
def public_comment(request):
    form = PublicCommentForm(request.POST)
    if form.is_valid():
        content = form.cleaned_data.get('content')
        news_id = form.cleaned_data.get('news_id')
        news = News.objects.get(id=news_id)
        comment = Comment.objects.create(content=content, news=news, author=request.user)
        serializer = CommentSerializer(comment)
        return restful.result(data=serializer.data)


# 新闻搜索
def search(request):
    q = request.GET.get('q')
    context = {}
    if q:
        newses = News.objects.filter(Q(title__icontains=q) | Q(content__icontains=q) | Q(author_userneme__icontains=q))
        context['newses'] = newses
    return render(request, 'search/search.html', context=context)
